import { createStore } from "vuex";
import { GlobalDataProps, GlobalErrorProps, ColumnProps } from "../utils/interface"
import axios from "axios";
import { getAndCommit, postAndCommit } from "../utils/request"
import { arrToObj } from "@/utils/utils"
// 记得加上GlobalDataProps泛型，否则user会被推断成{ isLogin: false }类型，然后mutations里面赋值错误
const store = createStore<GlobalDataProps>({
  state: {
    loading: false,
    user: { isLogin: false },
    columns: { data: [], currentPage: 0, count: 0 },
    columnItems: {
      list: [],
      author: {}
    },
    artical: {
      title: ''
    },
    token: localStorage.getItem('token') || '',
    error: { status: false }
  },
  mutations: {
    // login(state) {
    //   state.user = { ...state.user, isLogin: true, nickName: 'pangpang', _id: 'pang' }
    // },
    fetchColumns(state, rawData) {
      const { count, currentPage } = rawData.data
      const list: ColumnProps[] = rawData.data.list
      state.columns.count = count
      state.columns.currentPage = currentPage * 1
      state.columns.data.push(...list)
      console.log(state.columns);

    },
    fecthAuthorItems(state, rawData) {
      state.columnItems.author = {
        _id: rawData.author,
        avatar: rawData.avatar && rawData.avatar.url || '',
        nickName: rawData.title,
        description: rawData.description
      }
    },
    fetchColumnsItem(state, rawData) {
      state.columnItems = { ...state.columnItems, ...rawData.data }
    },
    fetchArtical(state, rawData) {
      state.artical = rawData.data
    },
    // 设置loading状态
    setLoading(state, isLoading) {
      state.loading = isLoading
    },
    login(state, rawData) {
      const { token } = rawData.data
      state.token = token
      localStorage.setItem('token', token)
      // 设置axios的header
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
    },
    fetchCurrentUser(state, rawData) {
      state.user = {
        isLogin: true,
        ...rawData.data
      }
    },
    // 设置错误状态信息
    setError(state, e: GlobalErrorProps) {
      state.error = e
    },
    // 创建文章
    createPost(state, rawData) {
      console.log(rawData);
    },
    // 获取当前文章信息，保存到state.artical
    fetchPost(state, rawData) {
      state.artical = rawData.data
    },
    deletePost(state, rawData) {
      console.log(rawData);
    },
    // 修改文章
    updatePost(state, rawData) {
      console.log('提交修改');
    }
  },
  actions: {
    // async fetchColumns(context) {
    //   const { data } = await axios.get('/api/columns')
    //   // context不是store对象本身，但是具有相似的功能
    //   context.commit('fetchColumns', data)
    // },
    fetchColumns({ state, commit }, params = {}) {
      console.log("params", params);

      const { currentPage = 1, pageSize = 6 } = params
      if (state.columns.currentPage < currentPage) {
        getAndCommit(`/api/columns?currentPage=${currentPage}&pageSize=${pageSize}`, 'fetchColumns', commit)
      }

    },
    // 只用到了context的commit方法，可以只把commit取出来
    async fecthAuthorItems({ commit }, cid) {
      const { data } = await axios.get(`/api/columns/${cid}`)
      commit('fecthAuthorItems', data.data)
    },
    fetchColumnsItem({ commit }, cid) {
      getAndCommit(`/api/columns/${cid}/posts`, 'fetchColumnsItem', commit)
    },
    fetchArtical({ commit }, cid) {
      getAndCommit(`/api/posts/${cid}`, 'fetchArtical', commit)
    },
    // 以上代码重复，可以封装一下 getAndCommit(url, mutationsName, commit)
    login({ commit }, payload) {
      return postAndCommit('/api/user/login', 'login', commit, payload)
    },
    fetchCurrentUser({ commit }) {
      getAndCommit('/api/user/current', 'fetchCurrentUser', commit)
    },
    // 组合Action,先login再fetch
    loginAndFetch({ dispatch }, loginData) {
      return dispatch('login', loginData).then(() => {
        return dispatch('fetchCurrentUser')
      })
    },
    createPost({ commit }, payload) {
      return postAndCommit('/api/posts', 'createPost', commit, payload)
    },
    fetchPost({ state, commit }, id) {
      const currentArtical = state.artical
      if (!currentArtical || !currentArtical.content) {
        return getAndCommit(`/api/posts/${id}`, 'fetchPost', commit)
      } else {
        return Promise.resolve({ data: currentArtical })
      }
    },
    // 删除文章
    async deletePost({ commit }, id) {
      const { data } = await axios.delete(`/api/posts/${id}`)
      commit("deletePost", data)
      return data
    },
    // 修改文章
    async updatePost({ commit }, { id, payload }) {
      const { data } = await axios.patch(`/api/posts/${id}`, payload)
      commit("updatePost", data)
      return data
    }
  },
  getters: {
    getColumns: (state) => {
      return state.columns.data
    },
    // 获取专栏信息
    getAuthorById: (state) => {
      return state.columnItems
    },
    // 获取文章详情
    getArtical: (state) => {
      return state.artical
    }
  }
})

export default store